﻿using HandyControl.Controls;
using HandyControl.Tools.Extension;
using Mapster;
using Minotaur.App.Core;
using Minotaur.App.Core.Attributes;
using Minotaur.App.Core.Exceptions;
using Minotaur.App.Core.Mvvm;
using Minotaur.App.Core.Redis;
using Minotaur.App.Domains.Dto;
using Minotaur.App.Domains.Model.Resouces;
using Minotaur.App.Domains.Request;
using Minotaur.App.Domains.ViewModel;
using Minotaur.App.Domains.ViewModel.Resources;
using Minotaur.App.Modules.Business.Service.Resources;
using Prism.Commands;
using Prism.Regions;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Minotaur.App.Modules.SystemSet.ViewModels
{
    public class ResourcesViewModel : WindowComputeViewModel
    {
        private readonly GlobalUserModel globalUserModel;
        private readonly IResourcesService resourcesService;
        private SystemControl.Views.Pagination pagination;
        public ResourcesViewModel(IRegionManager regionManager, IDbContext dbContext, IRedisClient _redisClient, GlobalUserModel globalUserModel, IResourcesService _resourcesService) : base(regionManager, dbContext, _redisClient)
        {
            this.globalUserModel = globalUserModel;
            this.resourcesService = _resourcesService;
        }

        #region 属性注册区域 

        private double menuStackPaneHeight;
        public double MenuStackPaneHeight { get => menuStackPaneHeight; set => SetProperty(ref menuStackPaneHeight, value); }
        public ObservableCollection<MenuInfoDto> _MenuInfos = new ObservableCollection<MenuInfoDto>();
        public ObservableCollection<MenuInfoDto> MenuInfos { get => _MenuInfos; set => SetProperty(ref _MenuInfos, value); }

        private ObservableCollection<Domains.ViewModel.Resources.ResourcesViewModel> _ResourceViews = new ObservableCollection<Domains.ViewModel.Resources.ResourcesViewModel>();

        public Modules.SystemControl.Views.SideMenu SideMenu { get; set; }

        /// <summary>
        /// 数据表列表信息
        /// </summary>
        public ObservableCollection<Domains.ViewModel.Resources.ResourcesViewModel> ResourceViews { get => _ResourceViews; set => SetProperty(ref _ResourceViews, value); }
        #endregion

        #region 命令注册
        /// <summary>
        /// 新增
        /// </summary>
        public ICommand AddCommand => new DelegateCommand<object>(AddAction);

        /// <summary>
        /// 搜索方法
        /// </summary>
        public ICommand SearchCommand => new DelegateCommand(SearchAction);

        public CheckBox AllCheckBox { get; set; }
        /// <summary>
        /// 批量删除
        /// </summary>
        public ICommand BatchDeleteCommand => new DelegateCommand(BatchDeleteAction);
        [GlobalLogAspect]
        private void BatchDeleteAction()
        {
            var ids = this.ResourceViews.Where(o => o.IsChecked).Select(o => o.Autoid).ToArray();
            if (!ids.Any())
            {
                Growl.Error("请选择要删除的数据!");
            }
            else
            {
                HandyControl.Controls.Growl.Ask("确定要删除当前数据吗？", isSumbit =>
                {
                    if (isSumbit)
                    {
                        this.OpendLoading = true;
                        Task.Run(delegate
                        {
                            try
                            {
                                var dbResult = this.dbContext.BusinessDb.UseSugarTranAsync(async () =>
                                {
                                    await this.dbContext.BusinessDb.Updateable<ResoucesInfo>()
                                    .SetColumns(o => o.IsDelete == true)
                                    .Where(o => ids.Contains(o.Autoid))
                                    .ExecuteCommandAsync();
                                    return true;
                                }).Result;
                                if (dbResult.IsSuccess)
                                {
                                    this.ShowSuccess = "删除资源信息成功！";
                                    InitTables();
                                }
                                else
                                {
                                    Growl.Error("删除资源信息失败！");
                                    this.Dispatcher.BeginInvoke(() =>
                                    {
                                        this.OpendLoading = false;
                                    });
                                }
                            }
                            catch (Exception ex)
                            {
                                OpendLoading = false;
                                if (ex is GlobalException)
                                    throw ex;
                                else
                                    throw new GlobalException(typeof(ResourcesViewModel), System.Reflection.MethodBase.GetCurrentMethod().Name, null, this.globalUserModel, ex.Message);
                            }

                        });
                    }
                    return true;
                });
            }
        }

        public TreeView MenuResType { get; internal set; }

        /// <summary>
        /// 菜单编码
        /// </summary>
        public string MenuCode { get; set; }

        private void SearchAction()
        {
            OpendLoading = true;
            InitTables();
        }
        /// <summary>
        /// 初始化列表数据
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        [GlobalLogAspect]
        private void InitTables()
        {
            this.Dispatcher.Invoke(delegate
            {
                this.IsRightDrawerOpen = false;
                if (AllCheckBox != null)
                {
                    AllCheckBox.IsChecked = false;
                }
            });

            Task.Run(() =>
            {
                try
                {
                    ResourcesRequest request = SearchViewModel.Adapt<ResourcesRequest>();
                    request.MenuCode = this.MenuCode;
                    ResourcesRespone tableInfo = this.resourcesService.InitResources(request).Result;
                    ObservableCollection<Domains.ViewModel.Resources.ResourcesViewModel> resutls = tableInfo is null
                    ? new ObservableCollection<Domains.ViewModel.Resources.ResourcesViewModel>()
                    : tableInfo.List.Adapt<ObservableCollection<Domains.ViewModel.Resources.ResourcesViewModel>>();
                    foreach (var item in resutls)
                    {
                        item.EditAction = this.EditAction;
                        item.EnableOrDisabledAction = this.EnableOrDisabledAction;
                        item.DeleteAction = this.DeleteAction;
                        item.DetaileAction = this.DetaileAction;
                        item.CreatorName = GetEmpCache(item.Creator.ToInt());
                    }
                    Dispatcher.BeginInvoke(() =>
                    {
                        if (resutls is null) return;
                        this.ResourceViews = resutls;
                        pagination.ViewModel.Total = tableInfo.TotalCount; 
                        OpendLoading = false;
                    });
                }
                catch (Exception ex)
                {
                    OpendLoading = false;
                    if (ex is GlobalException)
                        throw ex;
                    else
                        throw new GlobalException(typeof(ResourcesViewModel), System.Reflection.MethodBase.GetCurrentMethod().Name, null, this.globalUserModel, ex.Message);
                }
            });
        }

        private void DetaileAction(object obj)
        {
            throw new NotImplementedException();
        }


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void AddAction(object obj)
        {
        }

        /// <summary>
        /// 启用禁用
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        [GlobalLogAspect]
        private void EnableOrDisabledAction(object obj)
        {

            OpendLoading = true;
            Task.Run(async () =>
            {
                var results = true;
                Domains.ViewModel.Resources.ResourcesViewModel viewModel = (Domains.ViewModel.Resources.ResourcesViewModel)obj;
                bool status = viewModel.IsEnable.HasValue ? !viewModel.IsEnable.Value : false;
                var dbResult = await this.dbContext.BusinessDb.UseSugarTranAsync(async () =>
                {
                    await this.dbContext.BusinessDb.Updateable<ResoucesInfo>()
                    .SetColumns(o => o.IsEnable == status)
                    .Where(o => o.Autoid == viewModel.Autoid)
                    .ExecuteCommandAsync();
                    return true;
                });
                results = dbResult.IsSuccess;
                this.Dispatcher.Invoke(() =>
                {
                    this.IsRightDrawerOpen = false;
                    if (results)
                    {
                        OpendLoading = false;
                        this.ResourceViews.FirstOrDefault(o => o.Autoid == viewModel.Autoid).IsEnable = status;
                        Growl.Success(status ? "启用成功！" : "禁用成功！");
                        //this.MessageQueue = status ? "启用成功！" : "禁用成功！";
                    }
                    else
                    {
                        OpendLoading = false;
                        Growl.Error(status ? "启用失败！" : "禁用失败！");
                        //this.MessageQueue = status ? "启用失败！" : "禁用失败！";
                    }
                });
            });
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void EditAction(object obj)
        {
            throw new GlobalException(typeof(ResourcesViewModel), System.Reflection.MethodBase.GetCurrentMethod().Name, null, this.globalUserModel, "当前方法未实现！");
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="obj"></param>
        [GlobalLogAspect]
        private void DeleteAction(object obj)
        {
            OpendLoading = true;
            HandyControl.Controls.Growl.Ask("确定要删除当前数据吗？", isSumbit =>
            {
                if (isSumbit)
                {
                    Task.Run(() =>
                    {
                        var results = true;
                        Domains.ViewModel.Resources.ResourcesViewModel viewModel = (Domains.ViewModel.Resources.ResourcesViewModel)obj;
                        var dbResult = this.dbContext.BusinessDb.UseSugarTranAsync(async () =>
                        {
                            await this.dbContext.BusinessDb.Updateable<ResoucesInfo>()
                            .SetColumns(o => o.IsDelete == true)
                            .Where(o => o.Autoid == viewModel.Autoid)
                            .ExecuteCommandAsync();
                            return true;
                        }).Result;
                        results = dbResult.IsSuccess;
                        if (results)
                        {
                            this.ShowSuccess = "删除资源信息成功！";
                            InitTables();
                        }
                        this.Dispatcher.Invoke(() =>
                        {
                            this.IsRightDrawerOpen = false;
                            if (!results)
                            {
                                Growl.Error("删除资源信息失败！");
                            }
                            OpendLoading = false;
                        });
                    });
                }
                else
                {
                    OpendLoading = false;
                }
                return true;
            });
        }

        #endregion
        public override void InitData()
        {

            var resutls = globalUserModel.MenuInfos.Adapt<ObservableCollection<MenuInfoDto>>();
            if (!resutls.Any(o => o.Code == "common"))
            {
                resutls.Add(new MenuInfoDto()
                {
                    Code = "common",
                    Name = "公共资源",
                    IconKind = MaterialDesignThemes.Wpf.PackIconKind.AppleKeyboardCommand
                });
            }
            if (!resutls.Any(o => o.Code == "language"))
            {
                resutls.Add(new MenuInfoDto()
                {
                    Code = "language",
                    Name = "语言类型",
                    IconKind = MaterialDesignThemes.Wpf.PackIconKind.ArrowCollapseAll
                });
            }
            this.MenuInfos = resutls;
            if (this.MenuInfos.Any())
            {
                MenuCode = this.MenuInfos[0].Code;
                OpendLoading = true;
                InitTables();
            }
            pagination = this.ListPagination as SystemControl.Views.Pagination;
            pagination.ViewModel.PageEventClick += PageEventClick;
            //this.SideMenu.ItemsSource = null;
            this.SideMenu.OpendMenuClick -= OpendMenuClick;
            //this.SideMenu.ItemsSource = MenuInfos;
            this.SideMenu.OpendMenuClick += OpendMenuClick;

        }

        /// <summary>
        /// 打开相应的菜单资源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpendMenuClick(object sender, RoutedEventArgs e)
        {

            MenuInfoDto menuInfoDto = e.OriginalSource as MenuInfoDto;
            if (menuInfoDto is null) return;
            MenuCode = menuInfoDto.Code;
            this.SearchViewModel.PageIndex = 1;
            this.SearchViewModel.SearchQuery = "";
            this.SearchViewModel.PageSize = 20;
            pagination.ViewModel.PageSize = 20;
            OpendLoading = true;
            InitTables();
        }
        /// <summary>
        /// 分页操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PageEventClick(object sender, RoutedEventArgs e)
        {
            SearchViewModel searchViewModel = (SearchViewModel)e.OriginalSource;
            this.SearchViewModel.PageIndex = searchViewModel.PageIndex;
            this.SearchViewModel.PageSize = searchViewModel.PageSize;
            OpendLoading = true;
            this.InitTables();
        }

    }
}
